
#include "GraphicsDeviceManager.h"
#include "GraphicsDeviceSetting.h"
#include "../../FlameEngine/src/CoreEngine.h"

#pragma 

namespace FlameEngine
{
	GraphicsDeviceManager::GraphicsDeviceManager():m_pDXObject(NULL),m_pDevice(NULL)
	{
	}

	bool GraphicsDeviceManager::CreateDevice(GraphicsDeviceSetting& config,HWND wndHandle)
	{
		m_pDXObject = Direct3DCreate9(D3D_SDK_VERSION);
		if(!m_pDXObject)
		{
			MessageBox(0,"Direct3DCreate9 failed",0,0);
			return false;
		}

		m_d3dParams.BackBufferWidth = config.GetRenderTargetWidth(0);
		m_d3dParams.BackBufferHeight = config.GetRenderTargetHeight(0);
		m_d3dParams.BackBufferFormat = config.GetRenderTargetFormat(0);
		m_d3dParams.BackBufferCount = 1;
		m_d3dParams.MultiSampleType = config.GetMultisampleType();
		m_d3dParams.MultiSampleQuality = config.GetMultisampleQuality();
		m_d3dParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
		m_d3dParams.hDeviceWindow = wndHandle;
		m_d3dParams.Windowed = config.IsWindowd();
		m_d3dParams.EnableAutoDepthStencil = true;
		m_d3dParams.AutoDepthStencilFormat = config.GetDepthStencilFormat();
		m_d3dParams.Flags = 0;
		m_d3dParams.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
		m_d3dParams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

		HRESULT hr = m_pDXObject->CreateDevice(config.GetAdapterIndex(),config.GetDeviceType(),wndHandle,config.GetBehaviorFlags()
			,&m_d3dParams,&m_pDevice);
		if(SUCCEEDED(hr))
		{
			return true;
		}
		else
		{
			m_pDevice = NULL;
			return false;
		}
	}

	void GraphicsDeviceManager::ChangeDeviceSetting(GraphicsDeviceSetting& config)
	{
		if(m_pDevice != NULL)
		{
			m_d3dParams.BackBufferWidth = config.GetRenderTargetWidth(0);
			m_d3dParams.BackBufferHeight = config.GetRenderTargetHeight(0);
			m_d3dParams.BackBufferFormat = config.GetRenderTargetFormat(0);
			m_d3dParams.BackBufferCount = 1;
			m_d3dParams.MultiSampleType = config.GetMultisampleType();
			m_d3dParams.MultiSampleQuality = config.GetMultisampleQuality();
			m_d3dParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
			m_d3dParams.Windowed = config.IsWindowd();
			m_d3dParams.EnableAutoDepthStencil = true;
			m_d3dParams.AutoDepthStencilFormat =  config.GetDepthStencilFormat();
			m_d3dParams.Flags = 0;
			m_d3dParams.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
			m_d3dParams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

			m_pDevice->Reset(&m_d3dParams);
		}
	}
	
	HRESULT GraphicsDeviceManager::GetDeviceState()
	{
		return m_pDevice->TestCooperativeLevel();
	}

	HRESULT GraphicsDeviceManager::ResetDevice()
	{
		return m_pDevice->Reset(&m_d3dParams);
	}

	GraphicsDeviceManager::~GraphicsDeviceManager()
	{
		if(m_pDevice!=NULL)m_pDevice->Release();
		if(m_pDXObject!=NULL)m_pDXObject->Release();
	}
}